package com.patent.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.patent.common.ResultCode;
import com.patent.common.ResultData;
import com.patent.domain.po.User;
import com.patent.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

	private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

	@Autowired
	private UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
	                         Object handler) throws Exception {
		String userMobile = request.getParameter("userMobile");
		if(StringUtils.isNotBlank(userMobile)){
			User user = userService.selectByUserMobile(userMobile);
			if(user == null){
				returnErrorMessage(response,ResultCode.loginError.getCode(),"userMobile invalid");
				return false;
			}else{
				return true;
			}
		}else{
			returnErrorMessage(response,ResultCode.loginError.getCode(),"userMobile is null");
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
	                       ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
	                            Exception ex) throws Exception {

	}

	private void returnErrorMessage(HttpServletResponse response,String code, String errorMessage) throws IOException {
		ResultData resultData = new ResultData();
		resultData.setCode(code);
		resultData.setMsg(errorMessage);
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(resultData);
		out.print(json);
		out.flush();
	}
}
